package com.acme;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class BankClient {

	Socket requestSocket;
	ObjectOutputStream out;
	ObjectInputStream in;
	int serverPort = 6667;
	String address = "localhost";

	BankClient() {
	}

	void run() {
		try {
			requestSocket = new Socket(address, serverPort);
			System.out.println("Connected to " + address + " in port "
					+ serverPort);
			out = new ObjectOutputStream(requestSocket.getOutputStream());
			in = new ObjectInputStream(requestSocket.getInputStream());
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					System.in));
			String line = null;
			do {
				try {
					line = (String) in.readObject();
					System.out.println("Got answer from the server: \n" + line);
					System.out.println("Please type any request");
					line = reader.readLine();
					System.out.println("Sendeng your request to the server");
					sendMessage(line);
				} catch (ClassNotFoundException classNot) {
					System.out.println("data recieved in unknown format");
				} 
			} while (!line.equals("exit"));
		} catch (UnknownHostException unknownHost) {
			System.out.println("You are trying to connect to anunknown host");
		} catch (IOException ioException) {
			ioException.printStackTrace();
		} finally {
			try {
				in.close();
				out.close();
				requestSocket.close();
			} catch (IOException ioException) {
				ioException.printStackTrace();
			}
		}
	}
	
	void sendMessage(final String msg) {
		try {
			out.writeObject(msg);
			out.flush();
			System.out.println("Request sent: " + msg);
		} catch (IOException ioException) {
			ioException.printStackTrace();
		}
	}
	
	public static void main(final String args[]) {
		BankClient client = new BankClient();
		client.run();
	}
}
